#include "tcp_client.h"

// 全局变量定义
int client_socket = -1;
char server_msg_queue[MSG_QUEUE_SIZE][BUFFER_SIZE] = {0};
int msg_queue_front = 0;
int msg_queue_rear = 0;
pthread_mutex_t msg_mutex = PTHREAD_MUTEX_INITIALIZER;
int recv_thread_running = 0;
pthread_t recv_tid;

/**
 * 消息队列入队（线程安全）
 */
static int msg_queue_push(const char *msg) {
    pthread_mutex_lock(&msg_mutex);
    // 队列满则返回失败
    if ((msg_queue_rear + 1) % MSG_QUEUE_SIZE == msg_queue_front) {
        pthread_mutex_unlock(&msg_mutex);
        return -1;
    }
    strncpy(server_msg_queue[msg_queue_rear], msg, BUFFER_SIZE - 1);
    msg_queue_rear = (msg_queue_rear + 1) % MSG_QUEUE_SIZE;
    pthread_mutex_unlock(&msg_mutex);
    return 0;
}

/**
 * 消息队列出队
 */
int tcp_get_server_msg(char *buf, int buf_len) {
    if (buf == NULL || buf_len <= 0) return -1;
    
    pthread_mutex_lock(&msg_mutex);
    // 队列为空则返回失败
    if (msg_queue_front == msg_queue_rear) {
        pthread_mutex_unlock(&msg_mutex);
        return -1;
    }
    strncpy(buf, server_msg_queue[msg_queue_front], buf_len - 1);
    msg_queue_front = (msg_queue_front + 1) % MSG_QUEUE_SIZE;
    pthread_mutex_unlock(&msg_mutex);
    return 0;
}

/**
 * 接收线程：持续读取服务器消息，存入队列（只跳过自己的回声）
 */
static void *tcp_recv_thread(void *arg) {
    (void)arg;
    char recv_buf[BUFFER_SIZE] = {0};
    recv_thread_running = 1;

    while (recv_thread_running && client_socket != -1) {
        memset(recv_buf, 0, BUFFER_SIZE);
        ssize_t recv_len = recv(client_socket, recv_buf, BUFFER_SIZE - 1, 0);

        // 处理连接断开/接收失败
        if (recv_len <= 0) {
            if (recv_len == 0) {
                printf("TCP Client: 服务器断开连接\n");
                msg_queue_push("服务器已断开连接");
            } else {
                perror("TCP Client: 接收失败");
                msg_queue_push("接收消息失败，连接已断开");
            }
            close(client_socket);
            client_socket = -1;
            break;
        }
        recv_buf[recv_len] = '\0';

        // 关键：只跳过自己发送的 MY_CHAT: 回声，不跳过服务器的 CHAT: 回复
        if (strncmp(recv_buf, "MY_CHAT:", 7) == 0) {
            printf("TCP Client: 收到自己的回声消息，跳过显示\n");
            continue;
        }

        // 处理服务器消息：去掉 CHAT: 前缀后入队（服务器回复格式）
        char *msg_to_queue = recv_buf;
        if (strncmp(recv_buf, "CHAT:", 5) == 0) {
            msg_to_queue = recv_buf + 5;
        }

        msg_queue_push(msg_to_queue);
    }
    recv_thread_running = 0;
    pthread_exit(NULL);
}

/**
 * 初始化TCP连接（连接服务器+启动接收线程）
 */
int tcp_client_init(void) {
    if (client_socket != -1) return 0;

    // 创建socket
    client_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (client_socket == -1) {
        perror("TCP Client: 创建socket失败");
        return -1;
    }

    // 配置服务器地址
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);

    // 连接服务器
    if (connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        perror("TCP Client: 连接失败");
        close(client_socket);
        client_socket = -1;
        return -1;
    }
    printf("TCP Client: 连接服务器 %s:%d 成功\n", SERVER_IP, SERVER_PORT);

    // 启动接收线程（未运行时）
    if (!recv_thread_running) {
        if (pthread_create(&recv_tid, NULL, tcp_recv_thread, NULL) != 0) {
            perror("TCP Client: 创建线程失败");
            close(client_socket);
            client_socket = -1;
            return -1;
        }
        pthread_detach(recv_tid); // 分离线程，自动回收资源
    }
    return 0;
}

/**
 * 发送注册消息（原有功能，不修改）
 */
void tcp_send_register_success(const char *username, const char *password) {
    if (client_socket == -1 && tcp_client_init() == -1) {
        printf("TCP Client: 重连失败，无法发送注册消息\n");
        return;
    }

    char msg[128];
    snprintf(msg, sizeof(msg), "用户已注册 用户名:%s 密码:%s", username, password);
    if (send(client_socket, msg, strlen(msg), 0) == -1) {
        perror("TCP Client: 发送注册消息失败");
        close(client_socket);
        client_socket = -1;
        return;
    }
    printf("TCP Client: 发送注册消息：%s\n", msg);
}

/**
 * 发送登录消息（原有功能，不修改）
 */
void tcp_send_login_success(const char *username) {
    if (client_socket == -1 && tcp_client_init() == -1) {
        printf("TCP Client: 重连失败，无法发送登录消息\n");
        return;
    }

    char msg[128];
    snprintf(msg, sizeof(msg), "用户:%s成功登陆", username);
    if (send(client_socket, msg, strlen(msg), 0) == -1) {
        perror("TCP Client: 发送登录消息失败");
        close(client_socket);
        client_socket = -1;
        return;
    }
    printf("TCP Client: 发送登录消息：%s\n", msg);
}

/**
 * 发送人工聊天申请（原有功能，不修改）
 */
void tcp_send_chat_apply(void) {
    if (client_socket == -1) {
        if (tcp_client_init() != 0) {
            printf("TCP Client: 重连失败，无法发送人工聊天申请\n");
            return;
        }
    }

    char apply_msg[] = "APPLY:人工聊天申请";
    if (send(client_socket, apply_msg, strlen(apply_msg), 0) == -1) {
        perror("TCP Client: 发送人工聊天申请失败");
        close(client_socket);
        client_socket = -1;
        return;
    }
    printf("TCP Client: 已发送人工聊天申请\n");
}

/**
 * 发送聊天消息（带 MY_CHAT: 标记，用于区分回声）
 */
void tcp_send_chat_msg(const char *text) {
    if (client_socket == -1) {
        if (tcp_client_init() != 0) {
            printf("TCP Client: 重连失败，无法发送聊天消息\n");
            return;
        }
    }

    // 带标记发送，避免与服务器回复混淆
    char chat_msg[256];
    snprintf(chat_msg, sizeof(chat_msg), "MY_CHAT:%s", text);
    if (send(client_socket, chat_msg, strlen(chat_msg), 0) == -1) {
        perror("TCP Client: 发送聊天消息失败");
        close(client_socket);
        client_socket = -1;
        return;
    }
    printf("TCP Client: 已发送聊天消息：%s\n", text);
}

/**
 * 关闭TCP连接（原有功能，不修改）
 */
void tcp_client_close(void) {
    if (client_socket != -1) {
        recv_thread_running = 0;
        close(client_socket);
        client_socket = -1;
        printf("TCP Client: 关闭连接\n");
    }
}